local desc_huanhua_2v2 = [[
  ## 幻化之战 2v2版本简介

  ---

  ## 身份说明

  游戏由两名忠臣和两名反贼进行，胜利目标为击杀所有敌人。

  座位排列可能是忠-反-反-忠或者忠-反-忠-反，以及对应的反贼在一号位的情况。

  ---

  ## 附加规则

  第一回合角色摸牌阶段少摸一张牌。四号位多摸一张初始手牌。

  队友之间手牌相互可见。

  一名角色死亡后，其队友可以选择：1. 摸两张牌。2. 进行一次幻化。

  ---

  ## 新生

  所有角色只能保留1个技能。并且所有的角色的体力上限、体力值会被调整到4点、护甲会归零。

  ---

  ## 幻化

  每轮开始时，存活角色各自选择一项：1. 进行一次幻化（随机观看3个技能，选择其中1个技能获得）。2. 摸两张牌。

]]

local Blacklist = {"fenyong","gundam__juejing","rende"}

  --技能给予
local addSkills = function(room, player, skillName)
  local skill = Fk.skills[skillName]
  if skill.lordSkill and (player.role ~= "lord" or #room.players < 5) then
    return
  end
  if #skill.attachedKingdom > 0 and not table.contains(skill.attachedKingdom, player.kingdom) then
    return
  end
  room:handleAddLoseSkills(player, skillName, nil, false)
end
  --获取技能
local function huanhua_Newskill(room)
  local players = room.alive_players
  local n = #players
  local ChosenGenerals = {}
  for _, p in ipairs(players) do
    table.insert(ChosenGenerals, p.general)
  end
  local generals = Fk:getGeneralsRandomly(3 * n, Fk:getAllGenerals(), ChosenGenerals)
  local skills = {}
  for _, g in ipairs(generals) do
    for _, s in ipairs(g.skills) do
      if not (s.lordSkill or s.switchSkillName or s.frequency > 3 or table.contains(Blacklist, s.name)) then
        table.insertIfNeed(skills, s.name)
      end
    end
  end
  for _, p in ipairs(players) do
    local choices = { "DrawTwo" }
    for i = 1, math.min(3, #skills) do
      table.shuffle(skills)
      table.insert(choices, 1, table.remove(skills, 1))
    end
    p.request_data = json.encode({ choices, choices, "huanhua_choice", "#huanhua-choice:"..p.id, true })
  end

  room:notifyMoveFocus(players, "AskForChoice")
  room:doBroadcastRequest("AskForChoice", players)

  for _, p in ipairs(players) do
    local ChosenSkill
    if p.reply_ready then
      if p.client_reply ~= "DrawTwo"
        then ChosenSkill = p.client_reply
        addSkills(room, p, ChosenSkill)
      else
        p:drawCards(2, "DrawTwo")
      end
    else
      p:drawCards(2, "DrawTwo")
    end
  end
end
  --队友的遗产
local function huanhua_Reward(room, player)
  local players = room.alive_players
  local ChosenGenerals = {}
  for _, p in ipairs(players) do
    table.insert(ChosenGenerals, p.general)
  end
  local generals = Fk:getGeneralsRandomly(3, Fk:getAllGenerals(), ChosenGenerals)
  local skills = {}
  for _, g in ipairs(generals) do
    for _, s in ipairs(g.skills) do
      if not (s.lordSkill or s.switchSkillName or s.frequency > 3 or table.contains(Blacklist, s.name)) then
        table.insertIfNeed(skills, s.name)
      end
    end
  end
  local choices = {}
  table.shuffle(skills)
  for i = 1, math.min(3, #skills) do
    table.insert(choices, table.remove(skills, 1))
  end
  if #choices > 0 then
    local choice = room:askForChoice(player, choices, "huanhua_Reward", "#huanhua-choice", true)
    if not choice then choice = table.random(choices, 1) end
    room:handleAddLoseSkills(player, choice, nil, false)
  end
end

  --模式逻辑
local huanhua_2v2_getLogic = function()
  local huanhua_2v2_logic = GameLogic:subclass("huanhua_2v2_logic")

  function huanhua_2v2_logic:assignRoles()
    local room = self.room
    local roles = table.random {
      { "loyalist", "rebel", "rebel", "loyalist" },
      { "rebel", "loyalist", "loyalist", "rebel"},
    }

    for i = 1, 4 do
      local p = room.players[i]
      p.role = roles[i]
      p.role_shown = true
      room:broadcastProperty(p, "role")
    end

    room.players[1]:addBuddy(room.players[4])
    room.players[4]:addBuddy(room.players[1])
    room.players[2]:addBuddy(room.players[3])
    room.players[3]:addBuddy(room.players[2])

    self.start_role = roles[1]
    -- for adjustSeats
    room.players[1].role = "lord"
  end
  --选将
  function huanhua_2v2_logic:chooseGenerals()
    local room = self.room
    local generalNum = room.settings.generalNum
    local lord = room:getLord()
    room.current = lord
    lord.role = self.start_role

    local nonlord = room.players
    local generals = Fk:getGeneralsRandomly(#nonlord * generalNum)
    table.shuffle(generals)
    for _, p in ipairs(nonlord) do
      local arg = {}
      for i = 1, generalNum do
        table.insert(arg, table.remove(generals, 1).name)
      end
      p.request_data = json.encode({ arg, 1 })
      p.default_reply = table.random(arg, 1)
    end

    room:doBroadcastNotify("ShowToast", Fk:translate("huanhua_intro"))

    room:notifyMoveFocus(nonlord, "AskForGeneral")
    room:doBroadcastRequest("AskForGeneral", nonlord)

    for _, p in ipairs(nonlord) do
      if p.general == "" and p.reply_ready then
        local generals = json.decode(p.client_reply)
        local general = generals[1]
        room:setPlayerGeneral(p, general, true, true)
      else
        room:setPlayerGeneral(p, p.default_reply[1], true, true)
      end
      p.default_reply = ""
    end

    room:askForChooseKingdom(nonlord)
  end
  --体力初始化
  function huanhua_2v2_logic:broadcastGeneral()
    local room = self.room
    local players = room.players
  
    for _, p in ipairs(players) do
      assert(p.general ~= "")
      local general = Fk.generals[p.general]
      p.maxHp = 4
      p.hp = 4
      p.shield = 0
      -- TODO: setup AI here
  
      if p.role ~= "lord" then
        room:broadcastProperty(p, "general")
        room:broadcastProperty(p, "kingdom")
        room:broadcastProperty(p, "deputyGeneral")
      elseif #players >= 5 then
        p.maxHp = p.maxHp + 1
        p.hp = p.hp + 1
      end
      room:broadcastProperty(p, "maxHp")
      room:broadcastProperty(p, "hp")
      room:broadcastProperty(p, "shield")
    end
  end
  --技能初始化
  function huanhua_2v2_logic:attachSkillToPlayers()
    local room = self.room
    local players = room.players

    for _, p in ipairs(players) do
      local GetName = function(s)
        if not table.contains(Blacklist, s.name) then
          return s.name
        else
          return "zhiba"
        end
      end
      local skills = table.map(Fk.generals[p.general].skills, GetName)
      p.request_data = json.encode({ skills, skills, "huanhua_remainonlyone", "#huanhua_choice:"..p.id, true })
    end

    room:doBroadcastNotify("ShowToast", Fk:translate("huanhua_start"))

    room:notifyMoveFocus(players, "AskForChoice")
    room:doBroadcastRequest("AskForChoice", players)

    for _, p in ipairs(players) do
      local ChosenSkill
      if p.reply_ready then
        ChosenSkill = p.client_reply
        addSkills(room, p, ChosenSkill)
      end
    end
  end

  return huanhua_2v2_logic
end

  --幻化2v2
local huanhua_2v2_rule = fk.CreateTriggerSkill{
  name = "#huanhua_2v2_rule",
  priority = 0.001,
  refresh_events = {fk.DrawInitialCards, fk.DrawNCards, fk.GameOverJudge, fk.Deathed, fk.RoundStart},
  can_refresh = function(self, event, target, player, data)
    return target == player
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    if event == fk.DrawNCards then
      if player.seat == 1 and player:getMark(self.name) == 0 then
        room:addPlayerMark(player, self.name, 1)
        room:setTag("SkipNormalDeathProcess", true)
        data.n = data.n - 1
      end
    elseif event == fk.DrawInitialCards then
      if player.seat == 4 then
        data.num = data.num + 1
      end
    elseif event == fk.GameOverJudge then
      local winner = Fk.game_modes[room.settings.gameMode]:getWinner(player)
      if winner ~= "" then
        room:gameOver(winner)
        return true
      end
    elseif event == fk.RoundStart then
      huanhua_Newskill(room)
    else
      for _, p in ipairs(room.alive_players) do
        if p.role == player.role then
          local choices =  { "#DrawCard", "#NewSkill" }
          local choice = room:askForChoice(p, choices, "huanhua_Reward")
          if choice == "#NewSkill" then
            huanhua_Reward(room, p)
          else
            p:drawCards(2)
          end
        end
      end
    end
  end,
}
Fk:addSkill(huanhua_2v2_rule)

--游戏模式
local huanhua_2v2_mode = fk.CreateGameMode{
  name = "huanhua_2v2_mode",
  minPlayer = 4,
  maxPlayer = 4,
  rule = huanhua_2v2_rule,
  logic = huanhua_2v2_getLogic,
  surrender_func = function(self, playedTime)
    local surrenderJudge = { { text = "time limitation: 2 min", passed = playedTime >= 120 },
    { text = "2v2: left you alive", passed = table.find(Fk:currentRoom().players, function(p)
      return p.role == Self.role and p.dead
    end) and true } }
    return surrenderJudge
  end,
  winner_getter = function(self, victim)
    local room = victim.room
    local alive = table.filter(room.alive_players, function(p)
      return not p.surrendered
    end)
    local winner = alive[1].role
    for _, p in ipairs(alive) do
      if p.role ~= winner then
        return ""
      end
    end
    return winner
  end,
}
Fk:loadTranslationTable{
  ["huanhua_2v2_mode"] = "幻化 2v2",
  [":huanhua_2v2_mode"] = desc_huanhua_2v2,
  ["huanhua_remainonlyone"] = "选择一个技能保留",
  ["#huanhua_choice"] = "选择一个技能",
  ["huanhua_choice"] = "幻化",
  ["#huanhua_2v2_rule"] = "幻化",
  ["#DrawCard"] = "摸牌",
  [":#DrawCard"] = "摸两张牌。",
  ["#NewSkill"] = "获得技能",
  ["huanhua_Reward"] = "遗产",
  ["DrawTwo"] = "摸两张",
  [":DrawTwo"] = "放弃获得技能，摸两张牌",
  ["time limitation: 2 min"] = "游戏时长达到2分钟",
  ["2v2: left you alive"] = "你所处队伍仅剩你存活",
}

return huanhua_2v2_mode
